#!/usr/bin/env python3
#-*-coding:utf-8-*-
import os
import sys

def install():
	#切换目录至/data
	os.chdir('/data')
	#检查当前目录下是否有jdk安装包
	res = os.path.exists("jdk-8u181-linux-x64.tar.gz")
	if res != True:
		print("请先下载jdk安装包，默认版本是1.8.0_181")
		sys.exit(1)
	#解压，默认版本为1.8.0_181
	cmd = "tar -xzvf jdk-8u181-linux-x64.tar.gz -C /usr/local/"
	res = os.system(cmd)
	if res != 0:
		print("解压失败，请删除后重试")
		sys.exit(1)
	#配置环境变量
	f = open("/etc/profile.d/java.sh",mode="w")
	f.write("""JAVA_HOME=/usr/local/jdk1.8.0_181
JRE_HOME=$JAVA_HOME/jre 
PATH=$PATH:$JAVA_HOME/bin
CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar:$JRE_HOME/lib
LD_LIBRARY_PATH=$PATH:$JAVA_HOME/bin
export JAVA_HOME
export JRE_HOME
export PATH
export CLASSPATH
export LD_LIBRARY_PATH""")
	f.close()
	#给予执行权限
	os.chmod("/etc/profile.d/java.sh", 0755)
	#执行环境变量配置
	cmd = "source /etc/profile.d/java.sh"
	os.system(cmd)
	#检查是否配置成功
	cmd = 'which java'
	res = os.popen(cmd).read().strip("\n")
	java_bin = '/usr/local/jdk1.8.0_181/bin/java'
	if res != java_bin:
		print("配置失败，请检查")
		sys.exit(1)
	#检查jdk是否安装成功
	cmd = 'java -version'
	res = os.popen(cmd).read().strip("\n")
	print("请查看验证结果")
	print(res)
	

if __name__ == "__main__":
	install()
